# pylint: disable-msg=W0232,E1101
"""
@author: Sergiy Tsymbalyuk
"""

from hashlib import md5

from pylons.i18n import lazy_ugettext as _

from sqlalchemy import Column, Table, ForeignKey, UniqueConstraint
from sqlalchemy.types import Integer, String, Unicode, Date, Time, DateTime, Boolean
from sqlalchemy.orm import relation

from chowa.model.meta import Base, Session
from chowa.model.abstract import Person, person_full_name
from chowa.model.layout import Theme

__all__ = ['User', 'user_groups', 'Group', 'group_permissions', 'Permission', 'Visit']


group_permissions = Table('auth_group_permission', Base.metadata,
    Column('group_id', Integer,
           ForeignKey('auth_group.id'), primary_key=True),
    Column('permission_id', Integer,
           ForeignKey('auth_permission.id'), primary_key=True)
)


user_groups = Table('auth_user_group', Base.metadata,
    Column('user_id', Integer,
           ForeignKey('auth_user.id'), primary_key=True),
    Column('group_id', Integer,
           ForeignKey('auth_group.id'), primary_key=True)
)


class Group(Base):
    __tablename__ = 'auth_group'
    
    id = Column(Integer, primary_key=True)
    name = Column(String(32), unique=True, info={'verbose': _('Object|Name')})
    description = Column(Unicode(255), info={'verbose': _('Description')})
    permissions = relation('Permission', secondary=group_permissions)
    
    def __unicode__(self):
        return self.description if self.description else self.name
    
    def __repr__(self):
        return u'"%s"' % self.name


class User(Base):
    __tablename__ = 'auth_user'
    
    id = Column(Integer, primary_key=True)
    username = Column(String(16), unique=True, info={'verbose': _('Username')})
    _password = Column('password', String(80), info={'verbose': _('Password')})
    last_login = Column(DateTime, info={'verbose': _('Last login')})
    last_activity = Column(DateTime, info={'verbose': _('Last activity')})
    is_disabled = Column(Boolean, default=False, info={'verbose': _('Disabled')})
    is_online = Column(Boolean, info={'verbose': _('Online')})
    bad_password = Column(Boolean, info={'verbose': _('Bad password')})
    person_id = Column(Integer, ForeignKey(Person.id), info={'verbose': _('Person')})
    theme_id = Column(Integer, ForeignKey(Theme.id), info={'verbose': _('Theme')})
    
    groups = relation(Group, secondary=user_groups, backref='users')
    person = relation(Person, order_by=person_full_name)
    theme = relation(Theme)
    
    def validate_password(self, password):
        try:
            hashed_pass = md5(password)
        except:
            return False
        return self._password == hashed_pass.hexdigest()
    
    def __unicode__(self):
        try:
            return self.person.__unicode__()
        except:
            return self.username
    
    def short_name(self):
        try:
            return self.person.short_name()
        except:
            return self.username
    

class Permission(Base):
    __tablename__ = 'auth_permission'
    
    id = Column(Integer, primary_key=True)
    name = Column(String(32), unique=True, info={'verbose': _('Object|Name')})
    description = Column(Unicode(255), info={'verbose': _('Description')})
    
    def __unicode__(self):
        return self.description if self.description else self.name
    
    def __repr__(self):
        return u'"%s"' % self.name


class Visit(Base):
    __tablename__ = 'auth_visit'
    __table_args__ = (UniqueConstraint('ipv4', 'date'),)
    
    id = Column(Integer, primary_key=True)
    ipv4 = Column(String(15))
    user_agent = Column(String(255))
    date = Column(Date)
    first_activity = Column(Time)
    last_activity = Column(Time)
    user_id = Column(Integer, ForeignKey(User.id))
    
    user = relation(User)
